package com.chd.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import static com.chd.utils.RedisConstants.BLOOM_FILTER_KEY;
import static com.chd.utils.RedisConstants.CACHE_SHOP_KEY;


@Component
@Slf4j
public class CountingBloomFilter {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    private void init() {
        stringRedisTemplate.delete(BLOOM_FILTER_KEY);
        for (Long id = 1L; id <= 14; id++) {
            this.add(CACHE_SHOP_KEY + id);
        }
    }


    private int[] hashSeeds = {7, 11, 13, 31, 37}; // 自定义哈希种子数组

    // 插入元素
    public void add(String key) {
        for (int seed : hashSeeds) {
            int hash = hash(key, seed);
            String field = String.valueOf(hash);
            stringRedisTemplate.opsForHash().increment(BLOOM_FILTER_KEY, field, 1);
        }
    }

    // 查询元素是否存在
    public boolean mightContain(String key) {
        for (int seed : hashSeeds) {
            int hash = hash(key, seed);
            String field = String.valueOf(hash);
            Object o = stringRedisTemplate.opsForHash().get(BLOOM_FILTER_KEY, field);
            if (o == null) return false;
            Integer count = Integer.valueOf((String) o);
            if (count == 0) {
                return false; // 如果任何一个位置为0，则元素一定不存在
            }
        }
        return true; // 所有位置非0，元素可能存在
    }

    // 删除元素
    public void remove(String key) {
        for (int seed : hashSeeds) {
            int hash = hash(key, seed);
            String field = String.valueOf(hash);
            stringRedisTemplate.opsForHash().increment(BLOOM_FILTER_KEY, field, -1);
        }
    }

    // 简单哈希函数，使用种子计算
    private int hash(String key, int seed) {
        return Math.abs((key.hashCode() ^ seed) % 100000);
    }
}
